package pb

import (
	"chess_platform/internal/captcha"
	. "chess_platform/internal/common"
	"chess_platform/internal/token"
	"chess_platform/models/pb"
	"fmt"
	"image/png"
	"strings"
	"time"
)

//[pc]登录
type LoginController struct {
	BaseController
}

func (b *LoginController) URLMapping() {
	b.Mapping("Login", b.Login)
	b.Mapping("Captcha", b.Captcha)
	b.Mapping("Home", b.Home)
}

// @Title 图片验证码
// @Description 图片验证码
// @Success 0 {string} 图片
// @Failure 400
// @Failure 404
// @router /captcha [get]
func (b *LoginController) Captcha() {
	code := captcha.RandomString(4)
	b.SetSession("captcha", code)
	fmt.Println("----------------------------------")
	fmt.Println("sessionid:", b.CruSession.SessionID())
	fmt.Println("code", b.GetSession("captcha"))
	img := captcha.Captcha(code)
	b.Ctx.ResponseWriter.Header().Set("Content-Type", "image/png")
	png.Encode(b.Ctx.ResponseWriter, img)
}

// @Title 仅仅是测试
// @Description 仅仅是测试
// @Success 0 {string} 仅仅是测试
// @Failure 400
// @Failure 404
// @router /home [get]
func (b *LoginController) Home() {
	b.SetSession("test", "test")
	fmt.Println("----------------------------------")
	fmt.Println("code", b.GetSession("captcha"))
	b.Response()
}

// @Title 登录
// @Description 登录
// @Param   name     body    string  true      "用户名用于登录"
// @Param   password body    string  true      "密码"
// @Param   captcha  body    string  true      "图形验证码"
// @Success 0 {string} token 字符串,group_id等于0时为超级管理员
// @Failure 400
// @Failure 404
// @router /login [post]
func (b *LoginController) Login() {
	type Params struct {
		Name     string `json:"name"`
		Password string `json:"password"`
		Captcha  string `json:"captcha"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	b.Valid.Required(p.Name, "name").Message("用户名不能为空")
	b.Valid.Required(p.Password, "password").Message("密码不能为空")
	//b.Valid.Required(p.Captcha, "captcha").Message("验证码不能为空")
	if !b.VerifyParamsError() {
		return
	}

	//fmt.Println("sessionid:", b.CruSession.SessionID())
	if strings.ToLower(p.Captcha) != "" { //校验不能过,要删除掉session里的验证码
		//b.DelSession("captcha")
		//b.ResponseFail("验证码错误")
		//return
	}

	u, err := pb.UserInfoByName(p.Name)
	if err != nil {
		LogPc.Error(b.SystemError(err.Error()))

		return
	}
	if u.Uid == 0 || u.Name != p.Name || u.Password != Md5sum(p.Password) {
		b.Res.Code = ErrUserOrPassword
		b.Res.Msg = MsgErrUserOrPassword
		b.Response()
		return
	}

	//检查用户是否被冻结了，被冻结了不能登录
	if u.Frozen == 1 {
		b.Res.Code = ErrUserFrozen
		b.Res.Msg = "帐号已被冻结,请联系管理员"
		b.Response()
		return
	}

	tokenStr := token.Create(u.Uid, 0, TokenPB, 0)
	b.Res.Token = tokenStr
	data := map[string]interface{}{
		"real_name": u.RealName,
	}

	b.Res.Data = data
	b.ResponseSuccess("登录成功")
	//把token存在redis里
	key := fmt.Sprintf("%v%v", KeyPbTokenCache, u.Uid)
	RedisCache.Put(key, tokenStr, time.Duration(Secret.PbTokenCacheExpire)*time.Second)
	loginData := map[string]interface{}{
		"login_time": time.Now().Unix(),
	}
	pb.UpdateUser(loginData, u.Uid)
}
